//
//  GYSHomeVC.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2024/8/19.
//  Copyright © 2024 zwb. All rights reserved.
//

import UIKit

class GYSHomeVC: UIViewController {
    var collectionView: UICollectionView!
    var layout:UICollectionViewFlowLayout!
    fileprivate let expectMenuList = TenderAppear.shared.gysMenus
    var homeSize = 5
    var page = 1
    
    private var showMenuItemList = [MenuItem]()
    var tableView:UITableView = {
        let v = UITableView()
        v.backgroundColor = .clear
        return v
    }()
    private var keyWord = ""
    
    var bg1:UIView = {
        let v = UIView()
        v.backgroundColor = Theme.primaryColor()
        return v
    }()
    var bg2:UIView = {
        let v = UIView()
        v.layer.cornerRadius = KSGlobal.screenW
        v.backgroundColor = Theme.primaryColor()
        return v
    }()
    
    var feedVm = ZyaFeedVM()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 提示修改初始密码  （游客不用提示）
        let idenArr = USERINFO.roleListType.compactMap { $0.type }
        if UseInitialPassword && !idenArr.contains("8") {
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.8) {
                let vc = ModifyPasswordController(notReturn: true)
                self.navigationController?.pushViewController(vc, animated: true)
                
            }
        }
        
        MessageCenter.shared.refreshMessageItemStatus()
        self.showFloatV()
        self.insertIds2Update()
    }
    
    
    private var searchBar:UISearchBar?
    var dataArray =  [ZyaZtbContentModel]()
    
    var header:UIView = {
        var v = UIView()
        v.backgroundColor = .clear
        return v
    }()
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.removeFloatV()
    }
    private func setupSubviews() {
        self.view.backgroundColor = Theme.backgroudColor
        edgesForExtendedLayout = UIRectEdge()
        
        view.addSubview(bg1)
        bg1.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(KSGlobal.screenW)
            make.top.equalToSuperview()
            make.height.equalTo(100)
        }
        view.addSubview(bg2)
        bg2.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(KSGlobal.screenW * 2)
            make.top.equalTo(bg1.snp.bottom).offset(-50)
            make.height.equalTo(100)
        }
        configSearchBar()
        let collWidth = ScreenWidth - 12
        var row = (showMenuItemList.count - 1) / 3 + 1
        if row > 3 {
            row = 3
        }
        let itemSize = collWidth / 3
        
        let collHeight = CGFloat(row) * itemSize
        
        
        
        layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: itemSize, height: itemSize)
        
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        /// 详细菜单
        collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: collWidth, height: collHeight), collectionViewLayout: layout)
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .white
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(MenuCell.self, forCellWithReuseIdentifier: MenuCell.identifier)
        collectionView.layer.cornerRadius = 8
        collectionView.layer.masksToBounds = true
        header.addSubview(collectionView)
        header.frame = CGRect(x: 0, y: 0, width: collWidth, height: collHeight)
        tableView.tableHeaderView = header
        tableView.delegate = self
        tableView.dataSource = self
        tableView.layer.masksToBounds = true
        tableView.layer.cornerRadius = 8
        tableView.register(XSBaojiaCell.self, forCellReuseIdentifier: XSBaojiaCell.identifier)
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 250, right: 0)
        self.network()
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 90
        tableView.showsVerticalScrollIndicator = false
        tableView.mj_header = KSRefreshHeader {
            self.page = 1
            self.network()
        }
        tableView.mj_footer = KSRefreshFooter {
            self.page += 1
            self.network()
        }
        self.view.addSubview(tableView)
        tableView.frame = CGRect(x: 6, y: 50, width: KSGlobal.screenW - 12, height: KSGlobal.screenH)
    }
    func configSearchBar() {
        searchBar = TenderSearchBar(frame:CGRect(x:10,y:0,width:KSGlobal.screenW - 20,height:40))
        
        searchBar!.searchTextField.backgroundColor = UIColor(kshex: "#f5f5f5")
        searchBar!.searchTextField.layer.cornerRadius = 18
        searchBar!.searchTextField.layer.masksToBounds = true
        
        searchBar?.backgroundImage = UIImage()
        
        let toolbar = UIToolbar()
        toolbar.barStyle = UIBarStyle.default
        toolbar.sizeToFit()
        let buttonflexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
        let buttonDone = UIBarButtonItem(title: "完成", style: UIBarButtonItem.Style.done, target: self, action: #selector(doneClickss))
        buttonDone.tintColor = UIColor.black
        toolbar.setItems([buttonflexible, buttonDone], animated: true)
        
        searchBar!.inputAccessoryView = toolbar
        
        searchBar!.placeholder = "搜索报价信息"
        searchBar!.delegate = self
        
        let sBg = UIView(frame:CGRect(x:0,y:0,width:KSGlobal.screenW,height:50))
        sBg.addSubview(searchBar!)
        self.view.addSubview(sBg)
    }
    
    func network () {
        
        
        
        let api =  API.tender(.queryMytenderZbList(z_begin_dt: "", z_end_dt: "",z_province: "", z_city: "", z_price_min: "", z_price_max: "", page: "\(self.page)", size: "\(homeSize)", z_title: "", category: "",z_status: ""))
        
        KSNetwork.shared.doRequest(api,showHud: false) { (data:BaseResult<ZyaZtbContentModel>) in
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    if self.page == 1 {
                        self.dataArray.removeAll()
                    }
                    self.dataArray += infos
                    if infos.count < self.homeSize {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    } else {
                        self.tableView.mj_footer?.endRefreshing()
                    }
                    
                    self.insertIds2Update()
                }
                
            } else {
                
            }
            self.tableView.reloadData()
            self.tableView.mj_header?.endRefreshing()
            
        }
        
        
        
        
        
        
        
        
        
    }
    
    func insertIds2Update() {
        let ids = self.dataArray.compactMap{$0.idKey}
        
        GetNewestUtil_Z.shared.appendIds(ids: ids,type: .TB)
        
    }
    @objc func doneClickss() {
        self.searchBar!.resignFirstResponder()
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        toPerson()
        
        
        MessageCenter.shared.configRightItem(vc: self, type: .message, noticeType: .siliao)
        title = "供应商"
        
        feedVm.getProtocol {
            
        }
        feedVm.getZTBUnit {
            
        }
        
        
        
        
        let expectMenuItemList = expectMenuList.compactMap { one -> MenuItem? in
            let mArr = MenuPool.filter{ $0.desc.unwrap == one}
            return mArr.first
        }
        if DeveloperTool.shared.GetAllowAllLimit() {
            showMenuItemList = expectMenuItemList
        } else {
            showMenuItemList = expectMenuItemList.filter {  one -> Bool in
                if one.resId == "0" || one.resId == "" {
                    return true
                } else {
                    if let _ = LimitDic[one.resId.unwrap] {
                        return true
                    } else {
                        return false
                    }
                }
                
            }
        }
        setupSubviews()
        
        feedVm.queryEquity()
        
        feedVm.getMember()
        
        // 登录成功事件发出这个通知
        NotificationCenter.default.addObserver(self, selector: #selector(afterLogin), name: NSNotification.Name(rawValue: UPDATE_NOTIFICATION), object: nil)
        
        
        if waitGo2Model.complete == false {
            let topViewController = RouterUtils.currentTopViewController()
            zyago2TenderInfoVC(listType: waitGo2Model.type == 0 ? .TB : .JP, fromVC:topViewController!,idkey:waitGo2Model.id,innerType: waitGo2Model.type == 0 ? .zbListKHW :.jpListKHW)
        }
        
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(newestBillStatusNotification(_:)), name: Notification.Name(newestBillStatus_notification), object: nil)
        
        
    }
    @objc func newestBillStatusNotification(_ notification: Notification) {
        // 从通知中获取用户信息
        if let userInfo = notification.userInfo,
           let arr = userInfo["newestBillStatus_data"] as? [NewestModel_Z] {
            
            for i in 0..<self.dataArray.count {
                let ddd = arr.filter{$0.idKey == self.dataArray[i].idKey}
                
                if ddd.count > 0 {
                    self.dataArray[i].zParallel = ddd.first!.zParallel
                    if ddd.first!.zEndDate.unwrap != "" {
                        self.dataArray[i].zEndDate = ddd.first!.zEndDate
                    }
                    if ddd.first!.zOvertimedNum.unwrap != "" {
                        self.dataArray[i].zOvertimedNum = ddd.first!.zOvertimedNum
                    }
                    self.dataArray[i].zBidCount = ddd.first!.zBidCount
                    self.dataArray[i].zPriceRank = ddd.first!.zPriceRank
                    
                }
            }
            
            self.tableView.reloadData()
            
            
            
            
        }
    }
    deinit {
        
        NotificationCenter.default.removeObserver(self)
        
    }
    
    func showFloatV() {
        if MessageCenter.shared.clickShowArr_siliao.count > 0 {
            self.view.addSubview(MessageCenter.shared.floatV_siliao)
            let opts:UIView.AnimationOptions = [.autoreverse , .repeat,.allowUserInteraction]
            UIView.animate(withDuration: 1, delay: 0, options: opts, animations: {
                MessageCenter.shared.floatV_siliao.center.y -= 50
            }, completion: { _ in
                
            })
        }
    }
    func removeFloatV() {
        MessageCenter.shared.floatV_siliao.center.y += 50
        MessageCenter.shared.floatV_siliao.removeFromSuperview()
    }
    
    
    // MARK: - 登录成功后需要做的操作
    @objc func afterLogin() {
        updateAction(controller: self)
        MessageCenter.shared.getNotReadNotice {
            self.showFloatV()
            MessageCenter.shared.startShow(showType: "0", noticeType: .siliao)
        }
        feedVm.getDefaultAddr()
        
    }
    override var shouldAutorotate: Bool {
        return true
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.portrait
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return UIInterfaceOrientation.portrait
    }
}
extension GYSHomeVC:UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        keyWord = searchText
        self.tableView.mj_header?.beginRefreshing()
    }
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        
    }
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        
    }
}

extension GYSHomeVC: UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.dataArray.count
        
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        var one = self.dataArray[indexPath.row]
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: XSBaojiaCell.identifier, for: indexPath) as? XSBaojiaCell else {
            fatalError("cell error")
        }
        cell.makeConstrainsts()
        one.innerType = ZTBInnerType.zbListKHW
        
        one.listType = .TB
        cell.one = one
        cell.btnDtradeType.isHidden = false
        cell.chengjiaoImg.isHidden = true
        return cell
        
        
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        var idkey = self.dataArray[indexPath.row].idKey.unwrap
        
        
        zyago2TenderInfoVC(listType: TBandJPType.TB, fromVC:self,idkey:idkey,innerType:ZTBInnerType.zbListKHW)
        
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 36
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: KSGlobal.screenW - 12, height: 36))
        headerView.backgroundColor = .white
        headerView.setMutiBorderRoundingCorners(corner: [.topLeft,.topRight], number: 8)
        
        
        let title = UILabel(frame: CGRect(x: 10, y: 2, width: 70, height: 30))
        title.font = UIFont.systemFont(ofSize: 15)
        title.text = "正在进行"
        let dark = UIView()
        dark.backgroundColor = #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)
        dark.ks_x = title.ks_maxX
        dark.ks_y = title.ks_y + 8
        dark.ks_height = title.ks_height - 16
        dark.ks_width = 2
        headerView.addSubview(dark)
        
        let btn = UIButton(frame: CGRect(x: 88, y: 2, width: 40, height: 30))
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btn.tag = section
        btn.setTitleColor(.darkGray, for: .normal)
        btn.addTarget(self, action: #selector(viewAll(sender:)), for: .touchUpInside)
        btn.setTitle("更多", for: .normal)
        
        headerView.addSubview(btn)
        headerView.addSubview(title)
        return headerView
    }
    
    @objc func viewAll(sender:UIButton) {
        
        
        let vc = ZyaTenderTabbarVC(listType: .TB)
        self.navigationController?.pushViewController(vc, animated: true)
        
        
        
        
    }
}
extension GYSHomeVC: UICollectionViewDelegate, UICollectionViewDataSource {
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return showMenuItemList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MenuCell.identifier, for: indexPath) as! MenuCell
        cell.imageName = showMenuItemList[indexPath.row].imgStr
        cell.title = showMenuItemList[indexPath.row].title
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard checkIdentity(iType: .gys) else {
            KSToast("该身份无权限")
            return
        }
        let one = showMenuItemList[indexPath.row].enterFunc
        one!(self)
        
    }
    
}


func go2DZD_Z(controller:UIViewController) {
    let vc = ZyaDZDVC()
    controller.navigationController?.pushViewController(vc, animated: true)
    
}
func go2Member_Z(controller:UIViewController) {
    alertUtil(controller, title: "提醒",message: "需要先升级为\(memStr.unicode2Str())才能查看", operateS: [nameAction(name: "确认升级", action: { _ in
        let vc = PurchaseMemberVC()
        controller.navigationController?.pushViewController(vc, animated: true)
    })])
}
func go2DZHT_Z(controller:UIViewController) {
    let vc = ZyaEcontractVC()
    controller.navigationController?.pushViewController(vc, animated: true)
}
